import {
  reqGetCategory1List,
  reqGetCategory2List,
  reqGetCategory3List
} from '@/api/product/category'

const state = {
  // 分类id
  category1Id: '',
  category2Id: '',
  category3Id: '',
  // 分类列表
  category1List: [],
  category2List: [],
  category3List: []
}

const mutations = {
  GET_CATEGORY1_LIST: (state, category1List) => {
    state.category1List = category1List
  },
  GET_CATEGORY2_LIST: (state, { category2List, category1Id }) => {
    // 更新2级分类列表
    state.category2List = category2List
    // 更新1级分类id
    state.category1Id = category1Id
    // 清空3级分类列表
    state.category3List = []
    // 清空id
    state.category2Id = ''
    state.category3Id = ''
  },
  GET_CATEGORY3_LIST: (state, { category3List, category2Id }) => {
    state.category3List = category3List
    state.category2Id = category2Id
    state.category3Id = ''
  },
  SET_CATEGORY3ID(state, category3Id) {
    state.category3Id = category3Id
  },
  RESET(state) {
    state.category1List = []
    state.category2List = []
    state.category3List = []
    state.category1Id = ''
    state.category2Id = ''
    state.category3Id = ''
  }
}

const actions = {
  // 获取一级分类列表
  async getCategory1List({ commit }) {
    // 要获取的是data中的数据，所以直接结构出来
    const { data } = await reqGetCategory1List()
    commit('GET_CATEGORY1_LIST', data)
  },
  // 获取二级分类列表
  async getCategory2List({ commit }, category1Id) {
    // 要获取的是data中的数据，所以直接结构出来
    const { data } = await reqGetCategory2List(category1Id)
    commit('GET_CATEGORY2_LIST', { category2List: data, category1Id })
  },
  // 获取三级分类列表
  async getCategory3List({ commit }, category2Id) {
    // 要获取的是data中的数据，所以直接结构出来
    const { data } = await reqGetCategory3List(category2Id)
    commit('GET_CATEGORY3_LIST', { category3List: data, category2Id })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
